﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using SVC.client;
namespace UI.Forms
{
    public partial class openCard : FormBase1
    {
        bool updateLayout = false;
        private SVC.client.CardOpen_M m = null;
        BindingList<SVC.client.CardOpen_D> ds = null;
        BindingList<SVC.client.View_Combo_Lite> vcs = null;
        SVC.client.View_Combo_Lite selectcombo = null;
        private BindingList<View_BlankCards> vbcs = null;
        private optype ot;
        public openCard(CardOpen_M _m)
        {
            m = _m;
            if (m==null)
            {
                ot = optype.Add;
            }
            else
            {
                ot = optype.Update;
            }
            InitializeComponent();
            
        }
        #region 加载禁用
        private void loaddisabled()
        {
            gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gridView1.OptionsBehavior.Editable = false;
            gridpopmenu.Enabled = false;
            btn_orderImport.Enabled = false;

        }
        #endregion

        #region 加载启用
        private void loadEnabled()
        {
            gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gridView1.OptionsBehavior.Editable = true;
            gridpopmenu.Enabled = true;
            btn_orderImport.Enabled = true;

        }
        #endregion

        private void btn_orderImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (lue_Client.EditValue == null)
            {
                Comm.ShowAlert("请先选择客户！");
                return;
            }

            openRQ_select frm=new openRQ_select(new Guid(lue_Client.EditValue.ToString()));
            frm.FatherRefresh = importorder;
            frm.ShowDialog();
        }

        private void importorder(SVC.client.CardOpenRQ_M rm,BindingList<SVC.client.CardOpenRQ_D> rds)
        {
            m.ClientID = rm.ClientID;
            m.discount = 0;
            m.ischeck = false;
            m.isfinish = false;
            m.orderid = rm.pid;
            m.total = rm.total;
            m.balance = 0;
            foreach (CardOpenRQ_D rd in rds)
            {
                SVC.client.CardOpen_D d = new CardOpen_D();
                d.CardPrice = 0;
                d.amount = rd.amount;
                d.cno = rd.cno;
                d.ComboID = rd.ComboID;
                d.monthflag = rd.monthflag;
                d.pid = m.pid;
                d.price = rd.price;
                d.quantity = rd.quantity;
                d.remarks = rd.remarks;
                d.unit = rd.unit;
                d.yue = rd.yue;
                d.activeDate = rd.activeDate;
                ds.Add(d);
            }
            gridView1.BestFitColumns();
        }

        private void openCard_Load(object sender, EventArgs e)
        {
            loaddisabled();
            btn_WH.Enabled = false; 
            vbcs = my.bw.View_BlankCards_List(my.ACID);
            vcs = my.bw.View_Combo_lite_List("", my.ACID);
            lue_Client.Properties.DataSource = my.bw.View_Client_lite_List(false, my.ACID);
            lue_Client.Properties.DisplayMember = "ClientName";
            lue_Client.Properties.ValueMember = "ClientID";
            lue_ck.Properties.DataSource = my.bw.Warehouse_Get("", my.ACID);
            lue_ck.Properties.DisplayMember = "WarehouseName";
            lue_ck.Properties.ValueMember = "WarehouseID";
            rice_amount.Leave += new EventHandler(rice_amount_Leave);
            rise_quantity.Leave += new EventHandler(rise_quantity_Leave);

            rile_ComoID.DataSource = vcs;
            rile_ComoID.DisplayMember = "ComboName";
            rile_ComoID.ValueMember = "ComboID";
            rile_ComoID.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(rile_ComoID_EditValueChanging);
            rile_GoodCode.DataSource = vbcs;
            rile_GoodCode.DisplayMember = "GoodsName";
            rile_GoodCode.ValueMember = "GoodsCode";
            ribe_cno.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(ribe_cno_ButtonClick);
            BindingList<View_Emp_lite> emps = my.bw.View_Emp_lite_List("", my.ACID);
            lue_JSempid.Properties.DataSource = emps;
            lue_JSempid.EditValue = null;
            lue_opID.Properties.DataSource = emps;
            lue_opID.EditValue = my.emp_lite.EmplID;
            lue_WHer.Properties.DataSource = emps;
            

            ribe_phone.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(ribe_phone_ButtonClick);
            ribe_phone.MouseLeave += new EventHandler(ribe_phone_MouseLeave);
            gridView1.Layout += new EventHandler(gridView1_Layout);
            if (ot==optype.Add)
            {
                m = new SVC.client.CardOpen_M();
                ds = new BindingList<CardOpen_D>();
                dateEdit1.DateTime = DateTime.Now;
                btn_WH.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                pe_done.Visible = false;
                pe_checked.Visible = false;
            }
            else
            {
                ds = m.CardOpen_D;
                m.CardOpen_D.Clear();
                gridView1.OptionsBehavior.Editable = false;
                btn_OK.Enabled = false;
                gridView1.OptionsBehavior.Editable = false; btn_WH.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                lue_Client.EditValue = m.ClientID;
                lue_ck.EditValue = m.WarehouseID;
                lue_JSempid.EditValue = m.JSempid;
                lue_opID.EditValue = m.opID;
                lue_WHer.EditValue = m.WHer;
                pe_done.Visible = m.iWHfinished;
                pe_checked.Visible = m.ischeck;
                dateEdit1.DateTime = m.Pdate;
                te_pid.Text = m.pid;
                te_linkman.Text = m.linkman;
                te_remarks.Text = m.Remarks;
                te_tel.Text = m.tel;
                
            }
            gridControl1.DataSource = ds;
            


        }

        void rise_quantity_Leave(object sender, EventArgs e)
        {
            CardOpen_D d = gridView1.GetRow(gridView1.FocusedRowHandle) as CardOpen_D;
            if (d.monthflag)
            {
                string newvalue = "";
                if (gridView1.EditingValue != null)
                {
                    newvalue = gridView1.EditingValue.ToString();
                }
                else
                {
                    newvalue = gridView1.GetFocusedRowCellValue("quantity").ToString();
                }
                d.quantity = decimal.Parse(newvalue);
                d.amount = d.price * d.quantity;
                d.yue = vcs.Single(p => p.ComboID == d.ComboID).TCZ.Value * d.quantity;
                d.HJ = d.amount + d.CardPrice;
            }

        }

        void rice_amount_Leave(object sender, EventArgs e)
        {
            string newvalue = "";
            if (gridView1.EditingValue != null)
            {
                newvalue = gridView1.EditingValue.ToString();
            }
            else
            {
                newvalue = gridView1.GetFocusedRowCellValue("amount").ToString();
            }
            CardOpen_D d = gridView1.GetRow(gridView1.FocusedRowHandle) as CardOpen_D;
            d.amount = decimal.Parse(newvalue);
            d.price =  d.amount / d.quantity;
            d.HJ = d.amount + d.CardPrice;
        }

        void rile_ComoID_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (gridView1.FocusedRowHandle<0)
            {
                selectcombo = vcs.Single(p => p.ComboID == int.Parse(e.NewValue.ToString()));
            }
            else
            {
                View_Combo_Lite oldcombo = vcs.Single(p => p.ComboID == int.Parse(e.OldValue.ToString()));
                View_Combo_Lite newcombo = vcs.Single(p => p.ComboID == int.Parse(e.NewValue.ToString()));
                CardOpen_D d = gridView1.GetRow(gridView1.FocusedRowHandle) as CardOpen_D;
                if (newcombo.monthFlag)
                {
                    d.ComboID = newcombo.ComboID;
                    d.monthflag = newcombo.monthFlag;
                    d.price = newcombo.outprice.Value;
                    d.unit = "元/月";
                    d.yue = newcombo.TCZ.Value*d.quantity;
                    d.amount = d.price * d.quantity;
                    d.HJ = d.amount + d.CardPrice;
                }
                else
                {
                    d.ComboID = newcombo.ComboID;
                    d.monthflag = newcombo.monthFlag;
                    d.price = newcombo.outprice.Value;
                    d.unit = "张";
                    d.yue = 0;
                    d.amount = d.price * d.quantity;
                    d.HJ = d.amount + d.CardPrice;
                }
            }
            
        }

        void ribe_cno_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0) return;
            if (lue_ck.EditValue==null)
            {
                Comm.ShowAlert("请先选择仓库！");
                return;
            }
            CardOpen_D d=  gridView1.GetRow(gridView1.FocusedRowHandle) as SVC.client.CardOpen_D;
            if (d == null) return;
            if(d.ComboID==null)
            {
                Comm.ShowAlert("请先选择套餐！");
                return;
            }
            else
	        {
                SVC.client.Combo combo = my.bw.ComboByComboID_Get(d.ComboID,my.ACID);
                Select_BC_forClient frm = new Select_BC_forClient(lue_ck.EditValue.ToString(), new Guid(lue_Client.EditValue.ToString()), combo.CardGoodsCode);
                frm.FatherRefresh = setcno;
                frm.ShowDialog();
	        }
            
        }

        void setcno(SVC.client.Cards card)
        {
            gridView1.SetFocusedRowCellValue("cno", card.cno);
            if (!card.ClientID.HasValue)
            {
                decimal outprice = vbcs.Single(p => p.GoodsCode == card.GoodsCode).outprice.Value;
                gridView1.SetFocusedRowCellValue("CardPrice",outprice);
                
            }
        }

        #region 行位置改变
        private void gridView1_Layout(object sender, EventArgs e)
        {
            updateLayout = true;

            SetPosition();
            updateLayout = false;
        }

        private void SetPosition()
        {
            if (gridView1.OptionsView.NewItemRowPosition == NewItemRowPosition.Bottom && gridView1.SortInfo.GroupCount == 0)
            {
                gridView1.FocusedRowHandle = gridView1.RowCount - 2; ;
                gridView1.MakeRowVisible(gridView1.FocusedRowHandle, false);
            }
        }
        #endregion

        void ribe_phone_MouseLeave(object sender, EventArgs e)
        {

        }

        void ribe_phone_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0) return;
            CardOpen_D d= gridView1.GetRow(gridView1.FocusedRowHandle) as CardOpen_D;
            if (d!=null)
            {
                if (d.activeDate<dateEdit1.DateTime.Date)
                {
                    Comm.ShowErorr("请先选择激活日期");
                    return;
                }
                号码选择 frm = new 号码选择(d.ComboID,d.monthflag,d.yue,d.activeDate,d.cno);
                frm.FatherRefresh = setphone;
                frm.ShowDialog();
            }
            
        }
        void setphone(string phone, string cno)
        {
            ds.Single(p => p.cno == cno).phone = phone;
            gridView1.BestFitColumns();
        }

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            te_pid.Text = my.bw.getBillNO(my.emp_lite.shopcode, dateEdit1.DateTime, 4, my.ACID);
            m.pid = te_pid.Text;
            m.Pdate = dateEdit1.DateTime;
            foreach (CardOpen_D d in ds)
            {
                d.pid = m.pid;
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                gridView1.FocusedRowHandle = e.RowHandle;
            }
        }

        private void btn_OK_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dxValidationProvider1.Validate()&&ds.Count!=0)
            {
                foreach (CardOpen_D d in ds)
                {
                    if (string.IsNullOrEmpty(d.cno))
                    {
                        Comm.ShowErorr(string.Format("串号不能为空！"));
                        return;
                    }
                    if (string.IsNullOrEmpty(d.phone))
                    {
                        Comm.ShowErorr(string.Format("号码不能为空！"));
                        return;
                    }
                    if (d.activeDate==null)
                    {
                        Comm.ShowErorr(string.Format("卡片激活日期未设置，请检查！"));
                        return;
                    }
                    if (d.activeDate<dateEdit1.DateTime.Date)
                    {
                        Comm.ShowErorr("激活日期不能小于单据日期！");
                    }
                }
                m.balance = ds.Sum(p => p.HJ);
                m.ClientID = new Guid(lue_Client.EditValue.ToString());
                m.discount = 0;
                m.ischeck = false;
                m.isfinish = false;
                if (lue_JSempid.EditValue!=null)
                {
                    m.JSempid = new Guid(lue_JSempid.EditValue.ToString());
                }
                m.linkman = te_linkman.Text;
                m.opID = my.emp_lite.EmplID;
                m.Pdate = dateEdit1.DateTime;
                m.pid = te_pid.Text;
                m.Remarks = te_remarks.Text;
                m.tel = te_tel.Text;
                m.total = m.balance;
                m.WarehouseID = lue_ck.EditValue.ToString();
                string r = my.bw.openCard(m, ds, my.ACID);
                if (string.IsNullOrEmpty(r))
                {
                    reset();
                }
                else
                {
                    Comm.ShowErorr(r);
                }
            }
        }

        /// <summary>
        /// 重置控件
        /// </summary>
        private void reset()
        {
            lue_Checkempid.EditValue = null;
            lue_ck.EditValue = null;
            lue_Client.EditValue = null;
            lue_JSempid.EditValue = null;
            dateEdit1.DateTime = DateTime.Now;
            te_linkman.Text = "";
            te_remarks.Text = "";
            te_tel.Text = "";
            m = new CardOpen_M();
            m.pid = te_pid.Text;
            ds = new BindingList<CardOpen_D>();
            gridControl1.DataSource = ds;
        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            if (selectcombo != null)
            {
                gridView1.SetFocusedRowCellValue("ComboID", selectcombo.ComboID);
                gridView1.SetFocusedRowCellValue("CardPrice", 0);
                gridView1.SetFocusedRowCellValue("quantity", 1);
                if (selectcombo.monthFlag)
                {
                    gridView1.SetFocusedRowCellValue("unit", "元/月");
                    gridView1.SetFocusedRowCellValue("price", selectcombo.outprice);
                    gridView1.SetFocusedRowCellValue("amount", selectcombo.outprice);
                    gridView1.SetFocusedRowCellValue("monthflag", true);
                    gridView1.SetFocusedRowCellValue("HJ",selectcombo.outprice);
                    gridView1.SetFocusedRowCellValue("yue", selectcombo.TCZ);
                }
                else
                {
                    gridView1.SetFocusedRowCellValue("unit", "张");
                    gridView1.SetFocusedRowCellValue("price", 0);
                    gridView1.SetFocusedRowCellValue("amount", 0);
                    gridView1.SetFocusedRowCellValue("monthflag", false);
                    gridView1.SetFocusedRowCellValue("HJ", selectcombo.outprice);
                    gridView1.SetFocusedRowCellValue("yue", selectcombo.TCZ);
                }

                gridView1.SetFocusedRowCellValue("activeDate", "");
                selectcombo = null;

            }
            

        }

        #region 只能选择套餐
        private void gridView1_ShowingEditor(object sender, CancelEventArgs e)
        {

            if (gridView1.FocusedColumn.FieldName != "ComboID")
            {
                SVC.client.CardOpen_D model = (SVC.client.CardOpen_D)gridView1.GetRow(gridView1.FocusedRowHandle);
                if (model != null)
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;
                }
            }

        }
        #endregion


        private void lue_Client_EditValueChanged(object sender, EventArgs e)
        {
            if (lue_Client.EditValue != null)
            {
                loadEnabled();  //刷新数据源
            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            SVC.client.CardOpen_D d = gridView1.GetRow(e.RowHandle) as SVC.client.CardOpen_D;
            if (!d.monthflag && d.quantity!=1)
            {
                e.Valid = false;
                e.ErrorText = "非包月套餐数量必须为1";
                gridView1.SetColumnError(gridView1.Columns["quantity"], "非包月套餐数量必须为1");
            }
            if (d.quantity<=0)
            {
                e.Valid = false;
                e.ErrorText = "数量不能为零";
                gridView1.SetColumnError(gridView1.Columns["quantity"], "数量不能为零");
            }
            if (!string.IsNullOrWhiteSpace(d.cno))
            {
                if (ds.Count(p => p.cno == d.cno) > 1)
                {
                    e.Valid = false;
                    e.ErrorText = "本单据中已使用过此串号";
                    gridView1.SetColumnError(gridView1.Columns["cno"], "本单据中已使用过此串号");
                }
            }
            if (!string.IsNullOrWhiteSpace(d.phone))
            {
                if (ds.Count(p => p.phone == d.phone) > 1)
                {
                    e.Valid = false;
                    e.ErrorText = "本单据中已使用过此号码";
                    gridView1.SetColumnError(gridView1.Columns["phone"], "本单据中已使用过此号码");
                }
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (true)
            {
                
            }
            if (e.FocusedRowHandle>=0)
            {
                CardOpen_D d = gridView1.GetRow(e.FocusedRowHandle) as CardOpen_D;
                if (!string.IsNullOrWhiteSpace(d.phone))
                {
                    btn_WH.Enabled = true;
                }
            }
        }

    }
}